const XLSX = require('xlsx');
const path = require('path');
const fs = require('fs');
const { getCache, setCache } = require('./cacheManager');

const EXCEL_FILE_PATH = path.join(__dirname, '../data/books.xlsx');

/**
 * 获取图书Excel文件的最后修改时间
 * @returns {number} 最后修改时间戳
 */
const getExcelFileModifiedTime = () => {
  try {
    const stats = fs.statSync(EXCEL_FILE_PATH);
    return stats.mtimeMs;
  } catch (error) {
    console.error('Error getting books file modification time:', error);
    return 0;
  }
};

// 读取图书Excel文件并转换为JSON
const readBooksFile = () => {
  try {
    // 尝试从缓存获取数据
    const cachedData = getCache('books', 'data');
    if (cachedData) {
      return cachedData;
    }

    console.log('[BooksReader] Reading books.xlsx file from disk');
    const workbook = XLSX.readFile(EXCEL_FILE_PATH);
    if (!workbook || !workbook.SheetNames || workbook.SheetNames.length === 0) {
      throw new Error('无效的Excel文件格式');
    }

    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];

    if (!worksheet) {
      throw new Error('空的工作表');
    }

    const data = XLSX.utils.sheet_to_json(worksheet) || [];

    // 为每一行添加ID（如果不存在）
    const processedData = data.map((book, index) => {
      if (!book || typeof book !== 'object') {
        return null;
      }
      return {
        id: book.id || book.ISBN || book.bookId || `book_${index + 1}`,
        ...book
      };
    }).filter(book => book !== null); // 移除任何null条目

    // 将数据保存到缓存
    setCache('books', 'data', processedData);

    return processedData;
  } catch (error) {
    console.error('读取图书Excel文件时出错:', error);
    return []; // 返回空数组而不是抛出错误
  }
};

// 获取所有唯一的图书分类
const getBookCategories = () => {
  try {
    // 尝试从缓存获取分类数据
    const cachedCategories = getCache('books', 'categories');
    if (cachedCategories) {
      return cachedCategories;
    }

    console.log('[BooksReader] Computing book categories');
    const books = readBooksFile();
    const categories = new Set();

    books.forEach(book => {
      if (book.category) {
        categories.add(book.category.toLowerCase());
      }
    });

    const categoriesArray = Array.from(categories).sort();

    // 将分类数据保存到缓存
    setCache('books', 'categories', categoriesArray);

    return categoriesArray;
  } catch (error) {
    console.error('获取图书分类时出错:', error);
    return [];
  }
};

// 获取所有唯一的出版商及其计数
const getPublisherCounts = () => {
  try {
    // 尝试从缓存获取出版商数据
    const cachedPublishers = getCache('books', 'publishers');
    if (cachedPublishers) {
      return cachedPublishers;
    }

    console.log('[BooksReader] Computing book publisher counts');
    const books = readBooksFile();
    const publisherMap = new Map();

    books.forEach(book => {
      if (book.Publisher) {
        const publisher = book.Publisher.trim();
        publisherMap.set(publisher, (publisherMap.get(publisher) || 0) + 1);
      }
    });

    // 转换为数组并按计数降序排序
    const publisherCounts = Array.from(publisherMap.entries())
      .map(([name, count]) => ({ name, count }))
      .sort((a, b) => b.count - a.count);

    // 将出版商数据保存到缓存
    setCache('books', 'publishers', publisherCounts);

    return publisherCounts;
  } catch (error) {
    console.error('获取出版商统计时出错:', error);
    return [];
  }
};

// 搜索图书数据
const searchBooks = async (query) => {
  try {
    if (!query || typeof query !== 'string') {
      return [];
    }

    const books = await readBooksFile();
    if (!Array.isArray(books)) {
      return [];
    }

    console.log(`[BooksReader] Searching books for "${query}"`);
    const searchTerm = query.toLowerCase();

    return books.filter(book => {
      if (!book || typeof book !== 'object') {
        return false;
      }

      // 在所有字段中搜索
      return Object.entries(book).some(([key, value]) => {
        // 跳过id字段搜索
        if (key === 'id' || !value) return false;

        // 将值转换为字符串并搜索
        const strValue = String(value).toLowerCase();
        return strValue.includes(searchTerm);
      });
    });
  } catch (error) {
    console.error('搜索图书数据时出错:', error);
    return []; // 返回空数组而不是抛出错误
  }
};

module.exports = {
  readBooksFile,
  searchBooks,
  getBookCategories,
  getPublisherCounts
}; 
